package org.example.volunteerend.controller;

import java.util.Map;

import org.example.volunteerend.common.Result;
import org.example.volunteerend.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class SearchController {

    private final SearchService searchService;

    @Autowired
    public SearchController(SearchService searchService) {
        this.searchService = searchService;
    }

    /**
     * 综合搜索
     * 
     * @param keyword 搜索关键词
     * @param type 搜索类型（all/projects/users），默认为all
     * @param page 页码，默认为1
     * @param pageSize 每页数量，默认为10
     * @return 搜索结果
     */
    @GetMapping("/search")
    public Result<Map<String, Object>> search(
            @RequestParam String keyword,
            @RequestParam(required = false, defaultValue = "all") String type,
            @RequestParam(required = false, defaultValue = "1") Integer page,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        
        try {
            // 验证关键词不能为空
            if (keyword == null || keyword.trim().isEmpty()) {
                return Result.error("搜索关键词不能为空");
            }
            
            // 验证搜索类型
            if (!"all".equals(type) && !"projects".equals(type) && !"users".equals(type)) {
                return Result.error("无效的搜索类型，应为all、projects或users");
            }
            
            // 执行搜索
            Map<String, Object> result = searchService.search(keyword, type, page, pageSize);
            return Result.success("success", result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("搜索失败：" + e.getMessage());
        }
    }
} 